package indi.henry.demo.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import indi.henry.demo.service.RedisService;
import indi.henry.demo.service.ShortenService;
import lombok.RequiredArgsConstructor;

/**
 * @author Henry Hu Main controller for the shorten URL function
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/s")
public class ShortenController {

    private final ShortenService shortenService;

    private final RedisService redisService;

    @Value("${server.address}")
    private String address;

    @Value("${server.ssl.enabled}")
    private Boolean ssl;

    /**
     * 
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param id       The id input from the shortened URL user input in the browser
     *                 address bar
     * @throws IOException The possible exception prompted from Redis Template
     */
    @GetMapping("/{id}")
    public void redirectUrl(HttpServletRequest request, HttpServletResponse response, @PathVariable String id)
            throws IOException {
        response.sendRedirect(redisService.getUrlById(id));
    }

    /**
     * 
     * @param url URL that user input to be shortened
     * @return The shortened URL as the response content
     */
    @PostMapping
    public String setShortenUrl(@RequestBody String url) {

        url = shortenService.convertUrl(url);
        String id = shortenService.shortUrl(url);

        redisService.setUrlWithId(id, url);

        String protocol = Boolean.TRUE.equals(ssl) ? "https" : "http";
        return protocol + "://" + address + "/s/" + id;
    }
}
